<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>WebSocket chat client example</title>
  <link rel="icon" type="image/png" href="./favicon.png"/>
</head>
<body>
  <script>

  function init()
  {
    document.myform.url.value = "ws://localhost:8080/"
    document.myform.inputtext.value = "Hello World!"
    document.myform.disconnectButton.disabled = true
  }

  function doConnect()
  {
    websocket = new WebSocket(document.myform.url.value)
    websocket.onopen = function(evt) { onOpen(evt) }
    websocket.onclose = function(evt) { onClose(evt) }
    websocket.onmessage = function(evt) { onMessage(evt) }
    websocket.onerror = function(evt) { onError(evt) }
  }

  function onOpen(evt)
  {
    writeToScreen("connected\n")
    document.myform.connectButton.disabled = true
    document.myform.disconnectButton.disabled = false
  }

  function onClose(evt)
  {
    writeToScreen("disconnected\n")
    document.myform.connectButton.disabled = false
    document.myform.disconnectButton.disabled = true
  }

  function onMessage(evt)
  {
    writeToScreen("response: " + evt.data + '\n')
  }

  function onError(evt)
  {
    writeToScreen('error: ' + evt.data + '\n')

    websocket.close()

    document.myform.connectButton.disabled = false
    document.myform.disconnectButton.disabled = true
  }

  function doSend(message)
  {
    writeToScreen("sent: " + message + '\n')
    websocket.send(message)
  }

  function writeToScreen(message)
  {
    document.myform.outputtext.value += message
    document.myform.outputtext.scrollTop = document.myform.outputtext.scrollHeight
  }

  window.addEventListener("load", init, false)

  function sendText()
  {
    doSend(document.myform.inputtext.value)
  }

  function clearText()
  {
    document.myform.outputtext.value = ""
  }

  function doDisconnect()
  {
    websocket.close()
  }

  </script>
  <form name="myform">
    <p>
      <textarea name="url" cols="50" rows="1"></textarea>
    </p>
    <p>
      <input type="button" name=connectButton value="Connect" onClick="doConnect()">
      <input type="button" name=disconnectButton value="Disconnect" onClick="doDisconnect()">
    </p>
    <p>
      <textarea name="outputtext" cols="50" rows="20"></textarea>
    </p>
    <p>
      <textarea name="inputtext" cols="50" rows="1"></textarea>
    </p>
    <p>
      <input type="button" name=sendButton value="Send" onClick="sendText()">
      <input type="button" name=clearButton value="Clear" onClick="clearText()">
    </p>
 </form>
</body>
</html>
